<?php
declare (strict_types=1);

namespace app\service;

use app\model\User;
use app\model\UserDetails;
use app\model\UserImages;
use app\model\UserOrder;
use app\model\UserOrderPlan;
use app\model\UserOrderPlanGoods;
use app\traits\ServiceTrait;
use Exception;
use think\facade\Db;

/**
 * 用户
 * Class UserService
 * @package app\service
 */
class UserOrderService
{
    //模型，带命名空间
    public static $model = 'app\model\UserOrder';
    //模型主键
    public static $pk = 'order_id';
    //name字段名称
    public static $name = 'order_no';

    use ServiceTrait;


    /**
     * 列表
     * @param int $type
     * @return array
     */
    public static function queryListPage($type = 0)
    {
        $userOrderTable = UserOrder::$_table;
        $userTable = User::$_table;
        $userDetailTable = UserDetails::$_table;
        $list = Db::name($userOrderTable)
            ->alias('uo')
            ->field("uo.order_id orderId, uo.order_no orderNo, u.user_id userId, u.nick_name nickName, u.head_image headImage,u.sida_num sidaNum, ud.tixing, ud.fengge, ud.shengao, ud.tizhong, ud.nianling")
            ->join("$userTable u", 'uo.user_id = u.user_id', 'left')
            ->join("$userDetailTable ud", 'uo.user_id = ud.user_id', 'left')
            ->paginate(10)
            ->toArray();
        return $list;
    }

    /**
     * @param $data
     * @return array
     */
    public static function add($data)
    {
        $table_user_order = UserOrder::$_table;
        $orderId = $data['orderId'];
        $userOrder = Db::name($table_user_order)->where(['order_id' => $orderId])->find();
        if (empty($userOrder)) {
            throw new Exception('没有数据');
        }
        if (UserOrder::STATUS_END == $userOrder['status']) {
            throw new Exception('该搭配已完成');
        }
        $userId = $userOrder['user_id'];
        $images = $data['images'];
        $plans = $data['plans'];
        $table_images = UserImages::$_table;
        $table_user_order_plan = UserOrderPlan::$_table;
        $table_user_order_plan_goods = UserOrderPlanGoods::$_table;

        if (!empty($images)) {
            // 用户图片
            Db::name($table_images)->where(['user_id' => $userId])->delete();
            $userImagesData = [];
            foreach ($images as $image) {
                $userImagesData[] = [
                    'user_id' => $userId,
                    'img_url' => $image['imgUrl']
                ];
            }
            Db::name($table_images)->insertAll($userImagesData);
        }
        
        $userOrderPlanData = [];
        $userOrderPlanGoodsData = [];
        Db::name($table_user_order_plan)->where(['order_id' => $orderId])->delete();

        $date = date('Y-m-d H:i:s');
        foreach ($plans as $plan) {
            $userOrderPlanData['order_id'] = $orderId;
            $userOrderPlanData['fangan_name'] = $plan['fanganName'];
            $userOrderPlanData['say'] = $plan['say'];
            $planId = Db::name($table_user_order_plan)->insertGetId($userOrderPlanData);

            foreach ($plan['plansGoods'] as $p) {
                $userOrderPlanGoodsData[] = [
                    'plan_id' => $planId,
                    'goods_id' => 0,
                    'order_id' => $orderId,
                    'tb_goods_id' => $p['tbGoodsId'],
                    'title' => $p['title'],
                    'price' => $p['price'],
                    'pict_url' => $p['pictUrl'],
                    'tbk_item_url' => $p['tbkItemUrl'],
                    'tbk_tkl_url' => $p['tbkTklUrl'],
                    'create_time' => $date,
                ];
            }
        }

        Db::name($table_user_order_plan_goods)->where(['order_id' => $orderId])->delete();
        Db::name($table_user_order_plan_goods)->insertAll($userOrderPlanGoodsData);
    }

    /**
     * @param $data
     */
    public static function addOne($data)
    {
        $planId = $data['planId'] ?? 0;
        $orderId = $data['orderId'];
        $table_user_order_plan = UserOrderPlan::$_table;
        $table_user_order_plan_goods = UserOrderPlanGoods::$_table;
        $userOrderPlan = [];
        if ($planId) {
            $userOrderPlan = Db::name($table_user_order_plan)->where(['plan_id' => $planId])->find();
        }

        $date = date('Y-m-d H:i:s');
        if (empty($userOrderPlan)) {
            // 没有数据，则新增
            $userOrderPlanDataAdd = [];
            $userOrderPlanDataAdd['order_id'] = $orderId;
            $userOrderPlanDataAdd['fangan_name'] = $data['fanganName'];
            $userOrderPlanDataAdd['say'] = $data['say'];
            $planId = Db::name($table_user_order_plan)->insertGetId($userOrderPlanDataAdd);

            foreach ($data['plansGoods'] as $plan) {
                $userOrderPlanGoodsData[] = [
                    'plan_id' => $planId,
                    'goods_id' => 0,
                    'order_id' => $orderId,
                    'tb_goods_id' => $plan['tbGoodsId'],
                    'title' => $plan['title'],
                    'price' => $plan['price'],
                    'pict_url' => $plan['pictUrl'],
                    'tbk_item_url' => $plan['tbkItemUrl'],
                    'tbk_tkl_url' => $plan['tbkTklUrl'],
                    'create_time' => $date,
                ];
            }
            Db::name($table_user_order_plan_goods)->insertAll($userOrderPlanGoodsData);
        } else {
            // 修改
            $plans = $data['plansGoods'];

            $userOrderPlanGoodsData = [];
            Db::name($table_user_order_plan)->where(['plan_id' => $planId])->update([
                'fangan_name' => $data['fanganName'],
                'say' => $data['say'],
            ]);

            foreach ($plans as $plan) {
                $userOrderPlanGoodsData[] = [
                    'plan_id' => $planId,
                    'goods_id' => 0,
                    'order_id' => $orderId,
                    'tb_goods_id' => $plan['tbGoodsId'],
                    'title' => $plan['title'],
                    'price' => $plan['price'],
                    'pict_url' => $plan['pictUrl'],
                    'tbk_item_url' => $plan['tbkItemUrl'],
                    'tbk_tkl_url' => $plan['tbkTklUrl'],
                    'create_time' => $date,
                ];
            }

            Db::name($table_user_order_plan_goods)->where(['plan_id' => $planId])->delete();
            Db::name($table_user_order_plan_goods)->insertAll($userOrderPlanGoodsData);
        }
    }

    /**
     * @param $planId
     */
    public static function del($planId)
    {
        $table_user_order_plan = UserOrderPlan::$_table;
        $table_user_order_plan_goods = UserOrderPlanGoods::$_table;
        Db::name($table_user_order_plan)->where(['plan_id' => $planId])->delete();
        Db::name($table_user_order_plan_goods)->where(['plan_id' => $planId])->delete();
    }

    /**
     * 详情
     * @param $orderId
     * @return array
     */
    public static function detail($orderId)
    {
        $userOrderTable = UserOrder::$_table;
        $userTable = User::$_table;
        $userDetailTable = UserDetails::$_table;
        $userImagesTable = UserImages::$_table;
        $userOrderPlanTable = UserOrderPlan::$_table;
        $userOrderPlanGoodsTable = UserOrderPlanGoods::$_table;
        $detail = Db::name($userOrderTable)
            ->alias('uo')
            ->field("uo.order_id orderId, uo.order_no orderNo, u.user_id userId, u.nick_name nickName, u.head_image headImage,u.sida_num sidaNum, ud.xijie, ud.fuse, ud.tixing, ud.fengge, ud.shengao, ud.tizhong, ud.nianling")
            ->join("$userTable u", 'uo.user_id = u.user_id', 'left')
            ->join("$userDetailTable ud", 'uo.user_id = ud.user_id', 'left')
            ->where(['uo.order_id' => $orderId])
            ->find();
        if (empty($detail)) return [];
        $userId = $detail['userId'];

        $userImages = Db::name($userImagesTable)->where(['user_id' => $userId])->field('id,img_url imgUrl')->select()->toArray();
        if (empty($userImages)) {
            $userImages = [];
        }
        $detail['images'] = $userImages;

        $plans = Db::name($userOrderPlanTable)
            ->alias('op')
            ->field("op.*,opg.tb_goods_id,opg.title,opg.pict_url,opg.tbk_tkl_url,opg.tbk_item_url,opg.price")
            ->join("$userOrderPlanGoodsTable opg", 'op.plan_id = opg.plan_id', 'left')
            ->where(['op.order_id' => $orderId])
            ->select();
        $plansData = [];
        if (!empty($plans)) {
            foreach ($plans as $plan) {
                $plansData[$plan['plan_id']]['planId'] = $plan['plan_id'];
                $plansData[$plan['plan_id']]['orderId'] = $plan['order_id'];
                $plansData[$plan['plan_id']]['fanganName'] = $plan['fangan_name'];
                $plansData[$plan['plan_id']]['say'] = $plan['say'];
                $plansData[$plan['plan_id']]['goods'][] = [
                    'tbGoodsId' => $plan['tb_goods_id'] ?? '',
                    'title' => $plan['title'] ?? '',
                    'price' => $plan['price'],
                    'pictUrl' => $plan['pict_url'] ?? '',
                    'tbkTklUrl' => $plan['tbk_tkl_url'] ?? '',
                    'tbkItemUrl' => $plan['tbk_item_url'] ?? '',
                ];
            }
            $plansData = array_values($plansData);
        }
        $detail['plans'] = $plansData;
        return $detail;
    }
}
